package com.ebt.m.utils.android;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.ebt.m.AppInitService;
import com.ebt.m.data.entity.FileTypeBean;
import com.ebt.m.data.middle.EBTFileOption;
import com.ebt.m.data.middle.EBTFilePathHelper;
import com.ebt.m.data.middle.EBTFileReader;
import com.ebt.m.data.middle.EBTGetAdviceInfo;
import com.ebt.m.data.middle.PolicyNodeMeta;
import com.ebt.m.data.middle.ProductDatainfo;
import com.ebt.m.data.middle.Security;
import com.ebt.m.data.middle.datatype.EString;
import com.ebt.m.data.rxModel.RxDataRequest;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.exception.EBTException.EBTSoapHeaderException;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.UnZipUtils;
import com.ebt.m.utils.fileutils.DeCompressUtil;
import com.ebt.m.utils.fileutils.FileUtils;
import com.ebt.m.wiki.util.WikiUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipException;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * ProductDownloader(v 1.0.0) <br>
 * 主要功能 ：<br>
 * 1 检查设备网络状态<br>
 * 2 下载产品<br>
 * 3 返回下载信息<br>
 *
 * @author ZhanWu.Li
 * @create 2013.12.27
 */
public class DownloadController4Product extends Thread {
    /**
     * 设备唯一id
     */
    private static String uniqueAdviceStr = EBTGetAdviceInfo.getUid();

    private final String TAG = "Download4Product";
    /**
     * 文件url集合
     */
    private ArrayList<FileTypeBean> mUrlList = new ArrayList<FileTypeBean>();
    /**
     * 下载线程集合
     */
    private ArrayList<DonwloadThread> mThreadList = new ArrayList<DonwloadThread>();
    /**
     * 下载线程集合的映射存储
     */
    private Map<String, ArrayList<DonwloadThread>> filesThread = new HashMap<String, ArrayList<DonwloadThread>>();
    /**
     * 默认线程池最大数量
     */
    private int mDefautThreadCount = 3;// 默认子线程数为3个

    /**
     * 最大并发线程数量
     */
    private int MAX_THREAD;

    /**
     * 已下载文件长度
     */
    private double downloadSize = 0;
    /**
     * 下载文件总大小
     */
    private double filesSize = 0;

    /**
     * 完成的线程数
     */
    private int mDoneThreadCount = 0;

    /**
     * 需要开启线程数
     */
    private int mNeedThreadCount = 0;

    /**
     * 需要下载的文件数量
     */
    private int needDownFileCount = 0;
    /**
     * 已经下载的文件数量
     */
    private int downFileCount = 0;
    /**
     * 下载状态
     */
    private int mState = DownloaderConstants.DOWNLOAD_STATE_INIT;

    /**
     * 与Handler 之间传递消息
     */
    private Handler mHandler;
    /***
     * 线程池
     */
    private ExecutorService executor;
    /**
     * 线程状态-取消
     */
    private boolean canceled = false;

    private Bundle bundle = new Bundle();

    /**
     * 公司id
     */
    private String mCompanyId;
    /**
     * 产品id
     */
    private String mProductId;
    /**
     * mThreadList集合里下载失败的线程数量
     */
    private int failedDownCount;
    /**
     * 下载多张图片时，图片的索引
     */
    private int pictureIndex;


    /**
     * 下载结束后回调函数
     */
    private ProductDownloader.OnDownloadCallBack callBack;

    /**
     * 是否需要下载json
     */
    private boolean jsonDownloadSuccess;
    /**
     * 是否需要下载产品资源文件
     */
    private boolean isNeedDownloadRes;
    /**
     * 本地产品版本
     */
    private int localProductVersion;
    /**
     * 本地资源版本号
     */
    private int localResVersion;
    /**
     * 产品版本号
     */
    private String productVersion;
    /**
     * 资源版本号
     */
    private String resVersion;
    /**
     * webservice请求头部验证是否合法
     */
    private boolean isSoapHeaderInvalidate;

    /**
     * 产品条款解释下载地址
     */
    private String antoExplaintUrl;

    /**
     * 产品信息
     */
    private ProductDatainfo mProduct;
    /**
     * 产品图片数量
     */
    private int productPicCnt = 0;

    /**
     * 公司条款的下载数量
     */
    public static Map<String, Integer> companyAutoExpaintThreadNum = new ConcurrentHashMap<String, Integer>();


    /**
     * 初始化产品信息
     *
     * @param product
     * @param handler
     */
    public DownloadController4Product(ProductDatainfo product, Handler handler) {
        mProduct = product;
        MAX_THREAD = mDefautThreadCount;
        mProductId = product.ProductId + "";
        mCompanyId = product.CompanyId + "";
        this.localProductVersion = product.LocalProductVersion;
        this.localResVersion = product.LocalResourceVersion;
        if (product.compInfo != null) {
            this.antoExplaintUrl = product.compInfo.AutoExplanUrl;
        } else {
            this.antoExplaintUrl = null;
        }

        productVersion = "";
        resVersion = "";
        executor = Executors.newFixedThreadPool(MAX_THREAD);

        mHandler = handler;

    }

    /**
     * 通过给出的URL，创建下载文件需要的线程
     *
     * @throws IOException
     */
    public void initFileDownThread() throws IOException {

        mNeedThreadCount = 0;
        long fileSize = 0;
        pictureIndex = 0;
        for (int k = 0; k < mUrlList.size(); k++) {
            FileTypeBean fileType = mUrlList.get(k);
            String strUrl = fileType.getStrUrl();
            String filePath = getFileName(fileType);
            mNeedThreadCount++;
            SingleDownloaderThread servicethread = new SingleDownloaderThread(fileType, filePath, mCompanyId, mProductId);
            mThreadList.add(servicethread);
            filesThread.get(strUrl).add(servicethread);
        }
        filesSize = mNeedThreadCount;
    }

    @Override
    public void run() {
        super.run();
        String errorMsg = "";
        int errorNum = -1;
        if (!canceled) {
            boolean isReach = false;
            int count = 2;
            if (ConnectionDetector.getAPNType() == ConnectionDetector.NETWORK_STATE_NO_CONNECTION) {
                errorMsg = DownloaderConstants.STR_NETWORK_STATE_ERROR;
                errorNum = DownloaderConstants.INT_NETWORK_STATE_ERROR;
            } else {
                // if fail to connect, try once again
                while (!isReach && count > 0) {
                    if (ConnectionDetector.checkWikiResServer()) {
                        isReach = true;
                    }
                    count--;
                }
                if (!isReach) {
                    errorMsg = DownloaderConstants.STR_NETWORK_STATE_ERROR;
                    errorNum = DownloaderConstants.INT_NETWORK_STATE_ERROR;
                }
            }
            if (isReach) { // able to connect to server
                try {
                    // 下载json块，是否要下载json
                    startDownloadJson();
                    if (jsonDownloadSuccess) {
                        // 解析json，查看是否要下载资源
                        getDownloadResData();
                        if (isNeedDownloadRes) {
                            startDownloaderRes();
                        } else {
                            if (!canceled) {
                                downloaderDone();
                            }
                        }
                    } else {
                        if (!canceled) {
                            downloaderDone();
                        }

                    }

                    checkDownloadState();

                } catch (EBTSoapHeaderException e) {
                    e.printStackTrace();
                    mState = DownloaderConstants.DOWNLOAD_STATE_FAILED;
                    sendNetWorkErrorMsg(DownloaderConstants.STR_DOWNLOAD_NETWORK_SERVER, DownloaderConstants.INT_DOWNLOAD_NETWORK_SERVER);

                } catch (Exception e) {

                    e.printStackTrace();
                    mState = DownloaderConstants.DOWNLOAD_STATE_FAILED;
                    sendNetWorkErrorMsg(DownloaderConstants.STR_DOWNLOAD_ERROR, DownloaderConstants.INT_DOWNLOAD_ERROR);

                }
            } else {
                mState = DownloaderConstants.DOWNLOAD_STATE_FAILED;
                sendNetWorkErrorMsg(errorMsg, errorNum);
                return;
            }

        }
    }

    /***
     * 下载json数据块
     *
     * @throws Exception
     */
    private void startDownloadJson() throws Exception, JSONException, EBTSoapHeaderException {
        if (canceled) {
            return;
        }
        // 需要下载
        int needDownSize = 0;
        // 已经下载
        int mDownLength = 0;
        boolean isFinish = false;
        String mfilePath = EBTFilePathHelper.getJsonFileName(mCompanyId, mProductId);

        String fileName = mfilePath.substring(mfilePath.lastIndexOf('/') + 1);
        String filePath = mfilePath.substring(0, mfilePath.lastIndexOf("/"));

        fileName = fileName + ".temp";
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        File tempFile = new File(filePath, fileName);
        // tempFile.delete();
        tempFile.createNewFile();

        EBTAPI normalApi = AppInitService.getProductNormalApi();
        Response<ResponseBody> response = normalApi.getProductJson(RxDataRequest.getRestHeader(RxDataRequest.GETPRODUCTJSON, new Object[]{mProductId}), mProductId).execute();
        byte[] resultByte = response.body().bytes();
        String jsonStr = new String(resultByte);

        if (jsonStr == null || jsonStr.isEmpty()) {
            jsonDownloadSuccess = false;

        } else {
            if (DownloaderConstants.STR_DOWNLOAD_HEADER_ERROR.equals(jsonStr)) {// 验证失败
                jsonDownloadSuccess = false;
                // ProductDownloader.updateKey(userInfo);
                throw new EBTSoapHeaderException(DownloaderConstants.STR_DOWNLOAD_NETWORK_SERVER);
            } else {
                JSONTokener jsonParser = new JSONTokener(jsonStr);

                JSONObject obj = (JSONObject) jsonParser.nextValue();

                productVersion = obj.getString("productVersion");

                resVersion = obj.getString("resourceVersion");

                // fileMD5Value = obj.getString("FileMD5");

                String jsonbs64 = obj.getString("json");
                if (jsonbs64 != null && !jsonbs64.isEmpty()) {
                    jsonDownloadSuccess = true;

                    byte[] buffer = Security.AESDecrypt(jsonbs64, DownloaderConstants.AES_RESOURCE_ENCRYPT_KEY_4_DB).getBytes();
                    needDownSize = buffer.length;

                    InputStream inputStream = new ByteArrayInputStream(buffer);

                    RandomAccessFile outputStream = new RandomAccessFile(tempFile, "rw");
                    outputStream.setLength(0);
                    outputStream.seek(0);


                    int read = 0;
                    byte[] buf = new byte[1024 * 10];

                    while (false == isFinish && false == canceled) {

                        read = inputStream.read(buf);
                        if (read == -1) {
                            break;
                        }
                        outputStream.write(buf, 0, read);
                        // jsonStream.write(buf, 0, read);
                        mDownLength = mDownLength + read;
                        if (mDownLength == needDownSize) {
                            isFinish = true;
                            break;
                        }

                    }
                    outputStream.close();
                    // jsonStream .close();
                    inputStream.close();


                } else {
                    jsonDownloadSuccess = false;
                    isFinish = true;
                }

            }
        }

		/* 取消下载，删除下载文件 */
        if (true == canceled) {
            if (tempFile != null && tempFile.exists()) {
                FileUtils.deleteFile(tempFile);
            }
            return;
        }
        if (!isFinish && true != canceled) {

            mState = DownloaderConstants.DOWNLOAD_STATE_FAILED;
            sendNetWorkErrorMsg(DownloaderConstants.STR_DOWNLOAD_ERROR, DownloaderConstants.INT_DOWNLOAD_ERROR);
            return;
        }
    }

    /**
     * 开始下载资源
     *
     * @throws IOException
     */
    public void startDownloaderRes() throws IOException {
        if (ConfigData.DEBUG) {
            // Log.d(TAG, "startDownloader");
        }

        if (mState == DownloaderConstants.DOWNLOAD_STATE_DOWNLOADING || canceled) {// 如果正在下载就return
            return;
        }
        if (mState == DownloaderConstants.DOWNLOAD_STATE_FAILED) {
            return;
        }
        mState = DownloaderConstants.DOWNLOAD_STATE_DOWNLOADING;
        // 开启线程
        mDoneThreadCount = 0;// 初始化完成线程数
        // 只有在公司本地更新时间和服务器更新时间不一致，或者本地不存在 自动解析模板的时候才下载。
        //FIXME-DAMON-20160627
//        antoExpaintUrl = WikiUtils.PRODUCT_URL_PREFIX + mProductId + WikiUtils.PRODUCT_CLAUSE_URL_SUFFIX;

        if (mProduct.compInfo != null) {
            if (mProduct.compInfo.CompanyUpdateTime != null) {
                if (mProduct.compInfo.LocalCompanyUpdateTime == null || mProduct.compInfo.CompanyUpdateTime.compareTo(mProduct.compInfo.LocalCompanyUpdateTime) != 0) {
                    if (mUrlList != null && antoExplaintUrl != null && !antoExplaintUrl.isEmpty()) {

                        if (companyAutoExpaintThreadNum.get(mProduct.compInfo.companyId) == null) {
                            companyAutoExpaintThreadNum.put(mProduct.compInfo.companyId, 0);
                        }
                        int num = companyAutoExpaintThreadNum.get(mProduct.compInfo.companyId);

                        mUrlList.add(new FileTypeBean(antoExplaintUrl, DownloaderConstants.STR_FILE_TYPE_COMPANY_INTERPRETATION, num + ""));
                        filesThread.put(antoExplaintUrl, new ArrayList<DonwloadThread>());
                        num++;
                        companyAutoExpaintThreadNum.put(mProduct.compInfo.companyId, num);
                    }
                } else {
                    //FIXME-DAMON-20160627
//                    String filepath = EBTFilePathHelper.getCompanyInterpretationName(mCompanyId);
                    String filepath = EBTFilePathHelper.getCompanyInterpretationName(mCompanyId, mProductId);
                    File file = new File(filepath);
                    if (!file.exists()) {
                        if (mUrlList != null && antoExplaintUrl != null && !antoExplaintUrl.isEmpty()) {
                            if (companyAutoExpaintThreadNum.get(mProduct.compInfo.companyId) == null) {
                                companyAutoExpaintThreadNum.put(mProduct.compInfo.companyId, 0);
                            }
                            int num = companyAutoExpaintThreadNum.get(mProduct.compInfo.companyId);

                            mUrlList.add(new FileTypeBean(antoExplaintUrl, DownloaderConstants.STR_FILE_TYPE_COMPANY_INTERPRETATION, num + ""));
                            filesThread.put(antoExplaintUrl, new ArrayList<DonwloadThread>());
                            num++;
                            companyAutoExpaintThreadNum.put(mProduct.compInfo.companyId, num);
                        }
                    }
                }
            }
        }

        needDownFileCount = mUrlList.size();

        initFileDownThread();

        for (DonwloadThread thread : mThreadList) {
            executor.execute(thread);
        }

        // 启动一次顺序关闭，执行以前提交的任务，但不接受新任务
        executor.shutdown();

        long startMillis = System.currentTimeMillis();

        while (true) {
            // 15s之后如果还未结束下载任务，强制中止
            long currentMillis = System.currentTimeMillis();
            if (currentMillis - startMillis > 15000) {
                break;
            }

            if (executor.isTerminated()) {
                // 之前所有任务都完成了，独立下载新文件
                executor = Executors.newFixedThreadPool(MAX_THREAD);
                downloadSingleFile();
                break;
            }
        }


    }

    /**
     * 下载新文件
     */
    public void downloadSingleFile() {
        // 新文件路径
        String singleUrl = WikiUtils.PRODUCT_URL_PREFIX + mProductId + WikiUtils.PRODUCT_CLAUSE_URL_SUFFIX;
        FileTypeBean fileType = new FileTypeBean(singleUrl, DownloaderConstants.STR_FILE_TYPE_COMPANY_INTERPRETATION, "0");
        String filePath = getFileName(fileType);
        File file = new File(filePath);
        if (file.exists()){
            file.delete();
        }
        SingleDownloaderThread sdt = new SingleDownloaderThread(fileType, filePath, mCompanyId, mProductId);
        executor.execute(sdt);
    }

    /***
     * 读取json 文件，获取需要下载资源的路径
     */
    private void getDownloadResData() {
        if (canceled) {
            return;
        }

        String jsonPath = "";
        if (jsonDownloadSuccess) {
            jsonPath = EBTFilePathHelper.getJsonTempFileName(mCompanyId + "", mProductId + "");
        } else {
            jsonPath = EBTFilePathHelper.getJsonFileName(mCompanyId + "", mProductId + "");
        }
        File file = new File(jsonPath);
        String jsonValue = "";
        FileInputStream fin = null;
        try {
            if (file.exists()) {// 文件存在
                EBTFileOption option = new EBTFileOption();
                if (jsonDownloadSuccess) {
                    fin = EBTFileReader.initStream(jsonPath);
                    jsonValue = EBTFileReader.read(fin);

                } else {
                    jsonValue = option.EBTReadFile(jsonPath, EBTGetAdviceInfo.getUid());
                }

                JsonParser pa = new JsonParser();
                JsonElement jee = pa.parse(jsonValue);
                JsonElement je = jee.getAsJsonObject().get("productObj");
                jsonValue = je.getAsJsonArray().toString();
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                ArrayList<PolicyNodeMeta> pnmList = gson.fromJson(jsonValue, new TypeToken<ArrayList<PolicyNodeMeta>>() {
                }.getType());

                PolicyNodeMeta pnm = null;

                isNeedDownloadRes = true;
                pnm = getNodeByFieldName(DownloaderConstants.STR_FILE_TYPE_TERM, pnmList);
                if (pnm != null) {
                    mUrlList.add(new FileTypeBean(((EString) pnm.getEBTValue()).getValue(), DownloaderConstants.STR_FILE_TYPE_TERM));
                }

                pnm = getNodeByFieldName(DownloaderConstants.STR_FILE_TYPE_RULE, pnmList);
                if (pnm != null) {
                    mUrlList.add(new FileTypeBean(((EString) pnm.getEBTValue()).getValue(), DownloaderConstants.STR_FILE_TYPE_RULE));
                }

                pnm = getNodeByFieldName(DownloaderConstants.STR_FILE_TYPE_NODE_LIST, pnmList);
                if (pnm != null) {
                    mUrlList.add(new FileTypeBean(((EString) pnm.getEBTValue()).getValue(), DownloaderConstants.STR_FILE_TYPE_NODE_LIST));
                }


                //
                if (mProduct.Thumbnail != null) {
                    mUrlList.add(new FileTypeBean(mProduct.Thumbnail, DownloaderConstants.STR_FILE_TYPE_THUMBNAIL));
                }

                needDownFileCount = mUrlList.size();
                for (FileTypeBean fileUrl : mUrlList) {
                    filesThread.put(fileUrl.getStrUrl(), new ArrayList<DonwloadThread>());
                }


            } else {
                if (ConfigData.DEBUG) {
                    Log.d(TAG, "json file is not exists");
                }
                Bundle bundle = new Bundle();
                bundle.putString(DownloaderConstants.DOWNLOAD_ERROR_MSG, DownloaderConstants.STR_DOWNLOAD_ERROR_NO_RES);
                Message msg = new Message();
                msg.what = DownloaderConstants.DOWNLOAD_STATE_FAILED;
                msg.setData(bundle);
                if (mHandler != null) {

                    mHandler.sendMessage(msg);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            mState = DownloaderConstants.DOWNLOAD_STATE_FAILED;
            Bundle bundle = new Bundle();
            bundle.putString(DownloaderConstants.DOWNLOAD_ERROR_MSG, "解析出错");
            Message msg = new Message();
            msg.what = DownloaderConstants.DOWNLOAD_STATE_FAILED;
            msg.setData(bundle);
            if (mHandler != null) {

                mHandler.sendMessage(msg);
            }

        } finally {
            try {
                if (fin != null) {
                    EBTFileReader.close(fin);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }// 关闭流
            if (mState == DownloaderConstants.DOWNLOAD_STATE_FAILED) {
                return;
            }

        }

    }

    /**
     * 获取正在下载的文件的信息
     */
    public void getDownloadInformation() {

        downloadSize = 0;
        mDoneThreadCount = 0;
        downFileCount = 0;
        // filesSize = 0;
        failedDownCount = 0;
        // Log.d(TAG, "getDownloadInformation");
        for (DonwloadThread thread : mThreadList) {

            downloadSize = downloadSize + thread.getDownLength();
            // filesSize = filesSize + thread.getFileSize();
            if (thread.isFinish()) {
                mDoneThreadCount++;
            }
            if (thread.isThreadComplete() && !thread.isFinish()) {
                failedDownCount++;
            }
            if (thread.isSoapHeaderInvalidate()) {
                isSoapHeaderInvalidate = true;
            }
        }
        // 查看一个file是否下载完成
        for (FileTypeBean fileUrl : mUrlList) {
            boolean isDown = true;
            for (DonwloadThread thread : filesThread.get(fileUrl.getStrUrl())) {
                if (!thread.isFinish()) {

                    isDown = false;
                }
            }
            if (isDown) {
                downFileCount++;
            }
        }

    }

    /**
     * 下载完成,下载资源加密，删除临时文件。
     */
    private void downloaderDone() {

        if (jsonDownloadSuccess) {
            String jsonFilePath = EBTFilePathHelper.getJsonFileName(mCompanyId, mProductId);
            EBTFileOption option = new EBTFileOption();

            if (!option.EBTFullFileEncrypt(jsonFilePath + ".temp", uniqueAdviceStr, uniqueAdviceStr)) {
            } else {
            }

        }

        pictureIndex = 0;
        // 加密本地文件
        for (FileTypeBean fileType : mUrlList) {
            encryptFile(fileType, getFileName(fileType));
        }
        // onDownloaderListener.finishDownload();
        mState = DownloaderConstants.DOWNLOAD_STATE_DONE;
        bundle.putString(DownloaderConstants.DOWNLOAD_FINISH_MSG, DownloaderConstants.STR_DOWNLOAD_DOWN);

        int _productVersion = 0;
        int _resVersion = 0;
        if (productVersion != null && !productVersion.isEmpty()) {
            _productVersion = Integer.parseInt(productVersion);
        }
        if (productVersion != null && !productVersion.isEmpty()) {
            _resVersion = Integer.parseInt(resVersion);
        }
        if (_productVersion != 0) {
            bundle.putInt("ProductVersion", _productVersion);
        }
        if (_resVersion != 0) {
            bundle.putInt("ResourceVersion", _resVersion);
        }

        if (isNeedDownloadRes) {
            deleteOldProductPicture();
        }

		/*
         * if (ConfigData.DEBUG) { Log.d(TAG, "downloaderDone productVersion"
		 * + productVersion); Log.d(TAG, "downloaderDone resVersion" +
		 * resVersion); }
		 */

        if (mHandler != null) {
            Message dateMsg = mHandler.obtainMessage();
            dateMsg.what = DownloaderConstants.DOWNLOAD_STATE_DONE;
            dateMsg.setData(bundle);
            mHandler.sendMessage(dateMsg);
        }

    }

    /**
     * 取消下载
     */
    public void cancleDownload() {
        try {
            canceled = true;

            // downloadListener.interrupt();
            for (DonwloadThread thread : mThreadList) {
                thread.cancel();
                thread.interrupt();
            }
            mState = DownloaderConstants.DOWNLOAD_STATE_STOP;
            DownloadController4Product.this.interrupt();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 检查下载状态
     */
    private void checkDownloadState() {
        boolean isLoop = true;
        int what = 1;
        while (isLoop && !canceled) {
            if (what == 1) {
                Bundle bundle = new Bundle();
                // 如果需要显示下载进度
                // if (isNeedShowProcceseStop) {
                // bundle.putDouble(DownloaderConstants.DOWNLOAD_DOWNLENTH,
                // downloadSize);
                // } else {
                // bundle.putDouble(
                // DownloaderConstants.DOWNLOAD_DOWNLENTH, 0);
                // }
                bundle.putDouble(DownloaderConstants.DOWNLOAD_DOWNLENTH, downloadSize);
                bundle.putInt(DownloaderConstants.DOWNLOAD_NEDDDOWN_FILE_NUM, needDownFileCount);
                bundle.putInt(DownloaderConstants.DOWNLOAD_DOWN_FILE_NUM, downFileCount);
                bundle.putDouble(DownloaderConstants.DOWNLOAD_DOWN_FILE_TOTAL_SIZE, filesSize);

                // 如果没有下载失败
                if (failedDownCount == 0) {
                    if ((downloadSize < filesSize || (downloadSize == 0 && filesSize == 0)) || needDownFileCount != downFileCount) {// 未下载完成
                        what = 2;
                        try {
                            sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (mHandler != null && !canceled) {
                            Message dateMsg = new Message();
                            dateMsg.what = DownloaderConstants.DOWNLOAD_STATE_DOWNLOADING;
                            dateMsg.setData(bundle);
                            mHandler.sendMessage(dateMsg);
                        }

                    } else {
                        if (mHandler != null && !canceled) {
                            Message dateMsg = new Message();
                            dateMsg.what = DownloaderConstants.DOWNLOAD_STATE_DOWNLOADING;
                            dateMsg.setData(bundle);
                            mHandler.sendMessage(dateMsg);
                        }
                        // 下载完成
                        downloaderDone();
                        isLoop = false;
                    }
                } else {// 下载失败
                    if (mHandler != null) {
                        Message dateMsg = mHandler.obtainMessage();
                        dateMsg.what = DownloaderConstants.DOWNLOAD_STATE_FAILED;
                        mState = DownloaderConstants.DOWNLOAD_STATE_FAILED;
                        bundle.putString(DownloaderConstants.DOWNLOAD_ERROR_MSG, DownloaderConstants.STR_DOWNLOAD_ERROR);
                        dateMsg.setData(bundle);
                        mHandler.sendMessage(dateMsg);
                    }

                    cancleDownload();
                    isLoop = false;
                }

            } else {
                int anpType = ConnectionDetector.getAPNType();
                if (anpType != ConnectionDetector.NETWORK_STATE_NO_CONNECTION) {// 如果联网
                    getDownloadInformation();

                    what = 1;
                } else {

                    if (mHandler != null) {
                        Message dateMsg = mHandler.obtainMessage();
                        dateMsg.what = DownloaderConstants.DOWNLOAD_STATE_FAILED;
                        bundle.putString(DownloaderConstants.DOWNLOAD_ERROR_MSG, DownloaderConstants.STR_NETWORK_STATE_NO_CONNECTION);
                        dateMsg.setData(bundle);
                        mHandler.sendMessage(dateMsg);
                    }
                    isLoop = false;
                    cancleDownload();

                }

            }

        }// while结束
    }


    /**
     * 返回错误信息
     *
     * @param error
     * @param errorNum
     */
    private void sendNetWorkErrorMsg(String error, int errorNum) {
        bundle.putString(DownloaderConstants.DOWNLOAD_ERROR_MSG, error);
        bundle.putInt(DownloaderConstants.DOWNLOAD_ERROR_MSG_NUM, errorNum);

        if (mHandler != null) {
            Message dateMsg = mHandler.obtainMessage();
            dateMsg.what = DownloaderConstants.DOWNLOAD_STATE_FAILED;
            dateMsg.setData(bundle);
            mHandler.sendMessage(dateMsg);
        }
    }

    /**
     * 获取资源文件名称
     *
     * @param fileType
     * @return
     */
    private String getFileName(FileTypeBean fileType) {
        if (DownloaderConstants.STR_FILE_TYPE_JOSN.equals(fileType.getFileType())) {
            return EBTFilePathHelper.getJsonFileName(mCompanyId, mProductId);
        } else if (DownloaderConstants.STR_FILE_TYPE_NODE_LIST.equals(fileType.getFileType())) {
            return EBTFilePathHelper.getListFileName(mCompanyId, mProductId);
        } else if (DownloaderConstants.STR_FILE_TYPE_PRODUCT_PICTURE.equals(fileType.getFileType())) {
            String name = EBTFilePathHelper.getPictureFileName(mCompanyId, mProductId, pictureIndex);
            pictureIndex++;
            return name;
        } else if (DownloaderConstants.STR_FILE_TYPE_RULE.equals(fileType.getFileType())) {
            return EBTFilePathHelper.getRuleFileName(mCompanyId, mProductId);
        } else if (DownloaderConstants.STR_FILE_TYPE_TERM.equals(fileType.getFileType())) {
            return EBTFilePathHelper.getTermFileName(mCompanyId, mProductId);
        } else if (DownloaderConstants.STR_FILE_TYPE_JAR.equals(fileType.getFileType())) {
            return EBTFilePathHelper.getJarFileName();
        } else if (DownloaderConstants.STR_FILE_TYPE_THUMBNAIL.equals(fileType.getFileType())) {
            return EBTFilePathHelper.getThumbnailName(mCompanyId, mProductId);
        } else if (DownloaderConstants.STR_FILE_TYPE_PRODUCT_VOICE.equalsIgnoreCase(fileType.getFileType())) {
            return EBTFilePathHelper.getProductVoiceName(mCompanyId, mProductId, fileType.getStrUrl());
        } else if (DownloaderConstants.STR_FILE_TYPE_COMPANY_LOGO.equals(fileType.getFileType())) {
            return EBTFilePathHelper.getCompanyLogoName(mCompanyId);
        } else if (DownloaderConstants.STR_FILE_TYPE_COMPANY_PICTURE.equalsIgnoreCase(fileType.getFileType())) {
            return EBTFilePathHelper.getCompanyPictureName(mCompanyId, fileType.getIndex());
        } else if (DownloaderConstants.STR_FILE_TYPE_COMPANY_INTERPRETATION.equalsIgnoreCase(fileType.getFileType())) {
            //FIXME-DAMON-20160627
//            return EBTFilePathHelper.getCompanyInterpretationName(mCompanyId);
            return EBTFilePathHelper.getCompanyInterpretationName(mCompanyId, mProductId);
        } else if (DownloaderConstants.STR_FILE_TYPE_OTHER.equals(fileType.getFileType())) {
            String strUrl = fileType.getStrUrl();
            // Log.d(TAG, "getFileName strUrl:"+strUrl);
            String fileName = strUrl.substring(strUrl.lastIndexOf('/') + 1);

            // Log.d(TAG, "getFileName fileName:"+fileName);
            return EBTFilePathHelper.getMd5FileName(mCompanyId, mProductId, fileName);
        } else if (DownloaderConstants.STR_FILE_TYPE_CARD_THUMBNAIL.equals(fileType.getFileType())) {
            String strUrl = fileType.getStrUrl();
            // Log.d(TAG, "getFileName strUrl:"+strUrl);
            String fileName = strUrl.substring(strUrl.lastIndexOf('/') + 1);

            // Log.d(TAG, "getFileName fileName:"+fileName);
            return EBTFilePathHelper.getAgentCardThumbnail(strUrl);
        } else if (DownloaderConstants.STR_FILE_TYPE_PRODUCT_DB.equals(fileType.getFileType())) {
            return EBTFilePathHelper.getProductDbFileName(mCompanyId, mProductId);
        } else if (DownloaderConstants.STR_FILE_TYPE_PROPOSAL_BENEFIT_ATTACHMENT_ZIP_DB.equals(fileType.getFileType())) {
            String strUrl = fileType.getStrUrl();
            String fileNameWithSuffix = strUrl.substring(strUrl.lastIndexOf('/') + 1);// 带文件类型的文件名
            return EBTFilePathHelper.getProposalAttachmentZipFileName(mCompanyId, mProductId, fileNameWithSuffix);
        }
        return null;
    }

    /**
     * 对临时文件进行加密处理
     *
     * @param mFileType
     * @param mfilePath
     */
    private void encryptFile(FileTypeBean mFileType, String mfilePath) {
        EBTFileOption fileOption = new EBTFileOption();
        if (DownloaderConstants.STR_FILE_TYPE_OTHER.equalsIgnoreCase(mFileType.getFileType()) || DownloaderConstants.STR_FILE_TYPE_PRODUCT_PICTURE.equalsIgnoreCase(mFileType.getFileType())
                || DownloaderConstants.STR_FILE_TYPE_THUMBNAIL.equalsIgnoreCase(mFileType.getFileType())

                || DownloaderConstants.STR_FILE_TYPE_PRODUCT_VOICE.equalsIgnoreCase(mFileType.getFileType())
                || DownloaderConstants.STR_FILE_TYPE_COMPANY_PICTURE.equalsIgnoreCase(mFileType.getFileType())
                || DownloaderConstants.STR_FILE_TYPE_COMPANY_VIDEO.equalsIgnoreCase(mFileType.getFileType())
                || DownloaderConstants.STR_FILE_TYPE_COMPANY_LOGO.equalsIgnoreCase(mFileType.getFileType())

                || DownloaderConstants.STR_FILE_TYPE_CARD_THUMBNAIL.equalsIgnoreCase(mFileType.getFileType())) {

			/*if (fileOption.EBTFileNameEncrypt(mfilePath + ".temp", uniqueAdviceStr)) {// 加密文件名
                Log.e(TAG, "加密失败：file type: " + mFileType.getFileType() + " fileName:" + mFileType.getFilePath());
			}*/
            ;

        } else if (DownloaderConstants.STR_FILE_TYPE_JAR.equalsIgnoreCase(mFileType.getFileType())) {
            FileUtils.changeFileName(mfilePath + ".temp", mfilePath);

        } else if (DownloaderConstants.STR_FILE_TYPE_COMPANY_INTERPRETATION.equalsIgnoreCase(mFileType.getFileType())) {
            String temp = null;
            if ("0".equals(mFileType.getIndex())) {
                temp = mfilePath + ".temp";
            } else {
                temp = mfilePath + ".temp" + mFileType.getIndex();
            }
            if (fileOption.EBTFileNameEncrypt(temp, uniqueAdviceStr)) {

            }
        } else if (DownloaderConstants.STR_FILE_TYPE_PRODUCT_DB.equalsIgnoreCase(mFileType.getFileType())) {// 大费率表数据库压缩包下载完成后，解压
            FileUtils.changeFileName(mfilePath + ".temp", mfilePath);
            String parentPath;
            String tempDestDirName;
            // 取父文件夹
            // 非windows系统
            if (File.separator.equals("/")) {
                parentPath = mfilePath.substring(0, mfilePath.lastIndexOf("/"));
                // windows系统
            } else {
                parentPath = mfilePath.substring(0, mfilePath.lastIndexOf("\\"));
            }
            tempDestDirName = parentPath + File.separator + "temp";
            FileUtils.creatFile(tempDestDirName);
            try {
                DeCompressUtil.deCompress(mfilePath, tempDestDirName);
                File tempDestDir = new File(tempDestDirName);
                if (FileUtils.isFileExists(tempDestDir)) {
                    File[] files = tempDestDir.listFiles();
                    //大费率表不再使用
//                    for (File file : files) {
//                        if (file.getName().contains(".db")) {
//                            FileInputStream input = EBTFileReader.initStream(file.getAbsolutePath());
//                            // String rateDbPath =
//                            // parentPath+file.separator+ConfigData.DATABASE_RATE;
//                            String rateDbPath = parentPath + file.separator + EBTFilePathHelper.getRateDbName();
//                            FileUtils.copyFile(input, rateDbPath);
//                            break;
//                        }
//                    }

                    // FileUtils.deleteFile(mfilePath);
                    FileUtils.deleteFile(tempDestDirName);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (DownloaderConstants.STR_FILE_TYPE_PROPOSAL_BENEFIT_ATTACHMENT_ZIP_DB.equalsIgnoreCase(mFileType.getFileType())) {// 计划书利益全表数据库压缩包下载完成后，解压
            FileUtils.changeFileName(mfilePath + ".temp", mfilePath);// 文件改名
            String parentPath;
            String tempDestDirName;
            // 取父文件夹
            // 非windows系统
            if (File.separator.equals("/")) {
                parentPath = mfilePath.substring(0, mfilePath.lastIndexOf("/"));
                // windows系统
            } else {
                parentPath = mfilePath.substring(0, mfilePath.lastIndexOf("\\"));
            }
            tempDestDirName = parentPath + File.separator + "temp";
            FileUtils.creatFile(tempDestDirName);// 创建临时文件
            try {
                String fileNameWithFiledName = mFileType.getFilePath();// 用PolicyNodeMeta的filedName作为字段名
                // DeCompressUtil.deCompress(mfilePath,
                // tempDestDirName);//解压到临时文件夹，解压出来是db文件
                UnZipUtils.upZipFile(new File(mfilePath), tempDestDirName);
                File tempDestDir = new File(tempDestDirName);
                if (FileUtils.isFileExists(tempDestDir)) {
                    File[] files = tempDestDir.listFiles();
                    for (File file : files) {
                        if (file.getName().contains(".db")) {
                            FileInputStream input = EBTFileReader.initStream(file.getAbsolutePath());
                            // sd卡上路径
                            String proposalDbPath = parentPath + file.separator + EBTFilePathHelper.getEncriptProposalAttachmentDbName(fileNameWithFiledName);
                            FileUtils.copyFile(input, proposalDbPath);// 取出db文件
                            break;
                        }
                    }

                    // FileUtils.deleteFile(mfilePath);//删除源rar文件和临时文件
                    FileUtils.deleteFile(tempDestDirName);
                } else {
                }

            } catch (ZipException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            fileOption.EBTFullFileEncrypt(mfilePath + ".temp", uniqueAdviceStr, uniqueAdviceStr);
        }

    }

    /**
     * 根据fieldName获得单个节点
     *
     * @param
     * @return PolicyNodeMeta
     * @throws
     * @Description: 根据fieldName获得单个节点
     */
    public static PolicyNodeMeta getNodeByFieldName(String fieldName, ArrayList<PolicyNodeMeta> list) {
        if (DataValidation.isEmpty(fieldName)) {
            return null;
        }
        PolicyNodeMeta pnm = null;

        for (int i = 0; i < list.size(); i++) {

            pnm = list.get(i);
            if (pnm != null && fieldName.equalsIgnoreCase(pnm.getFieldName())) {
                return pnm;
            }
        }
        return null;
    }

    /**
     * 根据dataType获得节点集合
     *
     * @param
     * @return PolicyNodeMeta
     * @throws
     * @Description: 根据dataType获得节点集合
     */
    private static ArrayList<PolicyNodeMeta> getNodesByDataType(String dataType, ArrayList<PolicyNodeMeta> list) {
        ArrayList<PolicyNodeMeta> noteList = new ArrayList<PolicyNodeMeta>();
        if (DataValidation.isEmpty(dataType)) {
            return null;
        }
        PolicyNodeMeta pnm = null;

        for (int i = 0; i < list.size(); i++) {

            pnm = list.get(i);
            if (pnm != null && dataType.equalsIgnoreCase(pnm.geteDataType())) {
                noteList.add(pnm);
            }
        }
        return noteList;
    }

    /**
     * 删除旧的冗余的图片
     */
    private void deleteOldProductPicture() {

        if (productPicCnt > 0) {
            int index = productPicCnt;
            String filepath = EBTFilePathHelper.getPictureFileName(mCompanyId, mProductId, index);
            File file = new File(filepath);
            while (file.exists()) {
                file.delete();
                index++;
                filepath = EBTFilePathHelper.getPictureFileName(mCompanyId, mProductId, index);
                file = new File(filepath);
            }
        }

    }

    /**
     * 获取回调函数
     *
     * @return
     */
    public ProductDownloader.OnDownloadCallBack getCallBack() {
        return callBack;
    }

    /**
     * 设置回调函数
     *
     * @return
     */
    public void setCallBack(ProductDownloader.OnDownloadCallBack callBack) {
        this.callBack = callBack;
    }


    /**
     * 设置本地产品版本
     *
     * @param localProductVersion
     */
    public void setLocalProductVersion(int localProductVersion) {
        this.localProductVersion = localProductVersion;
    }


    /**
     * 设置本地资源版本
     *
     * @param localResVersion
     */
    public void setLocalResVersion(int localResVersion) {
        this.localResVersion = localResVersion;
    }

}
